<?php
/**
 * 数据导出类
 * @author 孙银川
 * @date   2017.12.30
 */

namespace app\common\model;
use think\Model;
use PHPExcel;
use PHPExcel_IOFactory;

class DataExport extends Model{

	/**
     * 导出excel表格
     * @param  array  $data   数据
     * @param  array  $title  标题行名称
     * @param  string $sheet  sheet名称
     */
	public function export($data, $title=[], $sheet=''){
        if($data){
            $obj = new PHPExcel();
            //横向单元格标识  
        	$cellName = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'AA', 'AB', 'AC', 'AD', 'AE', 'AF', 'AG', 'AH', 'AI', 'AJ', 'AK', 'AL', 'AM', 'AN', 'AO', 'AP', 'AQ', 'AR', 'AS', 'AT', 'AU', 'AV', 'AW', 'AX', 'AY', 'AZ');
        	//设置sheet名称
	        $obj->getActiveSheet(0)->setTitle($sheet);
	        //设置纵向单元格标识
	        $_row = 1;
	        if($title){
	            $i = 0;
	            foreach($title AS $v){   //设置列标题
	                $obj->setActiveSheetIndex(0)->setCellValue($cellName[$i].$_row, $v);
	                $i++;
	            }
	            $_row++;
	        }

	        //填写数据
            $i = 0;
            foreach($data as $val){
                $j = 0;
                foreach($val as $v){
                    $obj->getActiveSheet(0)->setCellValue($cellName[$j] . ($i+$_row), $v);
                    $j++;
                }
                $i++;
            }
            // ********************** download ************************
            $name = date("YmdH:i:s").'.xlsx';
            header('Content-Type: application/vnd.ms-excel; charset=utf-8');
            header('Pragma:public');
            header('Content-Type:application/x-msexecl;name="'.$name.'"');
            header('Content-Disposition:inline;filename="'.$name.'"');

            $objWriter = PHPExcel_IOFactory::createWriter($obj, 'Excel2007');
            $objWriter->save('php://output');
            die;
        }
	}
}
?>